package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author wuJiaWei
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void deductBalanceById(Long userId, Integer money) {
        //1.1 查询用户
        User user = getById(userId);
        //1.2 校验用户状态
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        //1.3 校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        //1.4 扣减余额
//        baseMapper.deductBalanceByIds(money, new QueryWrapper<User>().eq("id", userId));

        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance,remainBalance)
                .set(remainBalance == 0,User::getStatus,UserStatus.FREEZE)
                .eq(User::getId,userId)
                .eq(User::getBalance,user.getBalance()) //乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(UserQuery query) {
        return lambdaQuery()
                .like(query.getName() != null, User::getUsername, query.getName())
                .eq(query.getStatus() != null, User::getStatus, query.getStatus())
                .ge(query.getMinBalance() != null, User::getBalance, query.getMinBalance())
                .le(query.getMaxBalance() != null, User::getBalance, query.getMaxBalance())
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long userId) {
        // 1.查询用户
        User user = getById(userId);
        if (user == null || user.getStatus() == UserStatus.FREEZE) {
            throw new RuntimeException("用户状态异常");
        }
        // 2.查询收货地址
        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, userId)
                .list();
        // 3.封装返回
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        userVO.setAddresses(BeanUtil.copyToList(list, AddressVO.class));
        return userVO;

    }

    @Override
    public PageDTO<UserVO> queryUsersByPage(UserQuery query) {
        String name = query.getName();
        Integer status = query.getStatus();
        //1.构建分页条件
        Page<User> page = query.toMpPageDefaultSortByUpdateTime();
        //2.分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //3.封装VO结果
        //4.返回
        return PageDTO.of(p, user -> BeanUtil.copyProperties(user, UserVO.class));

//        return PageDTO.of(p,user->{
//            //1.拷贝基础属性
//            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
//            //2.处理特殊逻辑
//            vo.setUsername(vo.getUsername().substring(0, vo.getUsername().length() - 2) + "**");
//            return vo;
//        });
    }

}
